package com.le.tester.compared;

/**
 * createTime：2021/11/18 9:21
 * description：volatile测试，只保证可见性，不会有线程之间的上下文切换，比synchronized轻量，（i++）
 * result:同时开启20个线程来执行叠加1000次，只使用volatile的情况，将会出错，请看AtomicLongTest
 */
public class VolatileTest {
    private static final int THREAD_COUNT = 20;

    private static volatile int race = 0;

    public static void increment() {
        //提示不是原子性的操作
        race++;
    }

    public static void main(String[] args) {
        Thread[] threads = new Thread[THREAD_COUNT];
        for (int i = 0; i < THREAD_COUNT; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    increment();
                }
            });
            threads[i].start();
        }


        //等待所有线程叠加结束
        while (Thread.activeCount() > 1) {

            System.out.println("current thread activeCount is " + Thread.activeCount());
            Thread.yield();
        }


        System.out.println("race is " + race);
    }

}
